package com.remist.web.servlet;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.remist.common.Constant;
import com.remist.common.StringUtil;
import com.remist.service.UserService;

 
public class CheckLogin extends HttpServlet {

 
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

 
	public void doPost(HttpServletRequest request, HttpServletResponse response)	throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		String validateC = (String) request.getSession().getAttribute("validateCode");
		String veryCode = request.getParameter("veryCode");
		 
		if ( Constant.isIS_SHOW_VALIDATE_CODE() &&  (( validateC ==null || veryCode == null ) || "".equals(veryCode)) ) {
			response.sendRedirect("admin/login.action");
		} else {
			if ( Constant.isIS_SHOW_VALIDATE_CODE() ){
				if ( validateC.equals(veryCode)) {
				 String user = request.getParameter("user");
				 String password= request.getParameter("password");
				 if ( user!=null && !user.equals("") && password!=null && !password.equals("")){
					 ServletContext sc = getServletContext();
				     WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
					 UserService us= (UserService)wac.getBean("userService");
					 password = StringUtil.encode(password);
				     boolean flag = us.checkAdminUser(user,password);
				     if ( flag ){
				    	 request.getSession().setAttribute("userName", user);
				    	 response.sendRedirect("admin/index.action");
				     } else {
				    	 response.sendRedirect("admin/login.action");
				     }
				 }
				}else {
					response.sendRedirect("admin/login.action");
				}
			} else {
				 String user = request.getParameter("user");
				 String password= request.getParameter("password");
				 if ( user!=null && !user.equals("") && password!=null && !password.equals("")){
					 ServletContext sc = getServletContext();
				     WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(sc);
					 UserService us= (UserService)wac.getBean("userService");
					 password = StringUtil.encode(password);
				     boolean flag = us.checkAdminUser(user,password);
				     if ( flag ){
				    	 request.getSession().setAttribute("userName", user);
				    	 response.sendRedirect("admin/index.action");
				     } else {
				    	 response.sendRedirect("admin/login.action");
				     }
				 }
			}	
		}
		 
	}

}